import { getPluginsList } from "./build/plugins";
import { include, exclude } from "./build/optimize";
import { type UserConfigExport, type ConfigEnv, loadEnv } from "vite";
import {
  root,
  alias,
  wrapperEnv,
  pathResolve,
  __APP_INFO__
} from "./build/utils";
import { createProxy } from "./build/proxy";
import postcssPluginPx2rem from "postcss-plugin-px2rem"; // rem插件

export default ({ mode }: ConfigEnv): UserConfigExport => {
  const env = loadEnv(mode, root);
  // The boolean type read by loadEnv is a string. This function can be converted to boolean type
  const viteEnv = wrapperEnv(env);

  const {
    VITE_CDN,
    VITE_PORT,
    VITE_COMPRESSION,
    VITE_PUBLIC_PATH,
    VITE_PROXY,
    VITE_DROP_CONSOLE
  } = viteEnv;
  return {
    base: VITE_PUBLIC_PATH,
    root,
    resolve: {
      alias
    },
    // 服务端渲染
    server: {
      // 端口号
      port: VITE_PORT,
      host: "0.0.0.0",
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      proxy: createProxy(VITE_PROXY),
      // 预热文件以提前转换和缓存结果，降低启动期间的初始页面加载时长并防止转换瀑布
      warmup: {
        clientFiles: ["./index.html", "./src/{views,components}/*"]
      }
    },
    plugins: getPluginsList(VITE_CDN, VITE_COMPRESSION),
    // https://cn.vitejs.dev/config/dep-optimization-options.html#dep-optimization-options
    optimizeDeps: {
      include,
      exclude,
      // 强制预构建
      force: true,
      // 预构建缓存目录
      cacheDir: "node_modules/.vite"
    },
    build: {
      // https://cn.vitejs.dev/guide/build.html#browser-compatibility
      target: "es2015",
      sourcemap: false,
      // 启用 CSS 代码分割
      cssCodeSplit: true,
      // 启用最小化混淆
      minify: "terser",
      terserOptions: {
        compress: {
          keep_infinity: true,
          // Used to delete console in production environment
          drop_console: VITE_DROP_CONSOLE,
          drop_debugger: true
        }
      },
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve("./index.html", import.meta.url)
        },
        // 静态资源分类打包
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          // 手动分包策略
          manualChunks: {
            // 将 Vue 相关库打包在一起
            vue: ["vue", "vue-router", "pinia"],
            // 将 Element Plus 打包在一起
            elementPlus: ["element-plus"],
            // 将工具库打包在一起
            utils: ["axios", "dayjs", "js-cookie", "localforage"]
          }
        }
      }
    },
    define: {
      __BUILD_TIME__: JSON.stringify(new Date().toLocaleString()),
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    },
    css: {
      postcss: {
        plugins: [
          postcssPluginPx2rem({
            exclude: false,
            mediaQuery: false,
            minPixelValue: 2,
            propList: ["*"],
            // 排除哪些开头的如 .weui-button 等等
            selectorBlackList: [
              ".login-box",
              ".login-container",
              ".select-none",
              ".el-input__clear",
              ".left-collapse",
              ".title-wel"
            ],
            rootValue: { px: 16, rpx: 100 }
          })
        ]
      },
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/style/color.scss" as *;'
        }
      }
    }
  };
};
